import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import { t } from '@lingui/macro';
import React, { useEffect, useRef, useState } from 'react';
import { ENUMS, MAGIC_NUMBERS, column, toSelectDataSource } from './stores/definitions';
import TauTable from '@/components/TauTable';
import { uniqueId } from 'lodash';
import { useStore } from '@/hooks';
import { observer } from 'mobx-react-lite';
import { Button, Dialog } from '@alifd/next';
import MoreFuncDropDown from '@/components/MoreFuncDropDown';
import SendCarDrawer from './components/SendCarDrawer';
import TaskInfoDrawer from './components/TaskInfoDrawer';
import OrderInfoDrawer from './components/OrderInfoDrawer';
import FinishTaskDialog from './components/FinishTaskDialog';
import CancelCarDrawer from './components/CancelCarDialog';
import moment from 'moment';

const tableId = uniqueId('tauTable-');

function parseRegion(s) {
  if (!s?.length) return {};
  return { main: s[0]?.itemId, minor: s[1]?.itemId };
}

function CcTask() {
  const [modal, setModal] = useState([]);
  const { ccTaskStore: store } = useStore();
  const { TASK_STATE, DRIVER_STATE } = MAGIC_NUMBERS;
  const curRef = useRef();
  const changedRef = useRef();

  useEffect(() => {
    (async () => {
      await store.getCompanies();
    })();
  }, []);

  const handleOnSearch = (params) => {
    const { orderDate, startRegion: d1, endRegion: d2, ...searchArgs } = params?.values;
    const { startRegion, endRegion } = params?.valueObjects;
    const [from, to] = orderDate || [];
    const { main: startMainArea, minor: startMinorArea } = parseRegion(startRegion?.selectedPath || {});
    const { main: endMainArea, minor: endMinorArea } = parseRegion(endRegion?.selectedPath || {});
    store._mainArgs.search = {
      taskType: '0',
      from,
      to,
      startMainArea,
      startMinorArea,
      endMainArea,
      endMinorArea,
      ...searchArgs,
    };
  };

  // 点击打开派车
  const handleSendCar = (order) => {
    curRef.current = order;
    setModal(['sendCar']);
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    if (!_.isEmpty(changedRef.current)) {
      Dialog.confirm({
        content: t`放弃修改内容？`,
        onOk: () => setModal([]),
      });
      return;
    }
    setModal([]);
  };

  /**
   * @desc
   * @param {}
   * @return {}
   */
  const handleTableAction = (info, action) => {
    switch (action) {
      case 'viewTask':
        handleOpenTask(info);
        break;
      case 'viewOrder':
        handleOpenOrder(info);
        break;
      case 'finishTask':
      case 'pickUpPassenger':
      case 'pickedPassenger':
      case 'arrive':
        handleOpenFinishTask(info, action);
        break;
      case 'sendCar':
        handleSendCar(info);
        break;
      case 'cancelSendCar':
        handleOpenCancelCar(info);
        break;
      case 'editTask':
        handleEditTask(info);
        break;
      default:
        break;
    }
  };

  const handleOpenTask = (info) => {
    curRef.current = info;
    setModal(['viewTask']);
  };

  const handleOpenOrder = (taskInfo) => {
    curRef.current = taskInfo;
    setModal(['viewOrder']);
  };

  const handleOpenFinishTask = (taskInfo, action) => {
    curRef.current = taskInfo;
    setModal(['changeTaskState', action]);
  };

  const handleOpenCancelCar = (taskInfo) => {
    curRef.current = taskInfo;
    setModal(['cancelSendCar']);
  };

  const handleEditTask = (taskInfo) => {
    curRef.current = taskInfo;
    setModal(['editTask']);
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        searchItems={[
          { // 字典tree级联选择
            name: 'startRegion',
            type: 'dict-tree',
            props: { placeholder: t`始发区域`, changeOnSelect: true, dictId: 'region', maxLevel: 2, style: { minWidth: '160px' } },
          },
          {
            name: 'endRegion',
            type: 'dict-tree',
            props: { placeholder: t`结束区域`, changeOnSelect: true, dictId: 'region', maxLevel: 2, style: { minWidth: '160px' } },
          },
          {
            name: 'orderDate',
            type: 'date-range',
            props: {
              placeholder: [t`开始日期`, t`结束日期`],
            },
          },
          {
            name: 'states',
            type: 'select',
            props: {
              placeholder: t`任务状态`,
              dataSource: toSelectDataSource(ENUMS.states),
              mode: 'multiple',
            },
          },
          {
            name: 'carrierCompany',
            type: 'select',
            props: {
              placeholder: t`承运公司`,
              dataSource: store.companies,
              style: { width: 160 },
            },
          },
        ]}
        keywordSearch={{
          placeholder: t`请输入关键字搜搜`,
        }}
        className="action-panel"
      />
      <div className="content">
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store._mainArgs.pg.page}
          pageSize={store._mainArgs.pg.size}
          total={store._mainArgs.total}
          sort={store._mainArgs.tableSort}
          onFetch={(pg) => { store._mainArgs.pg = pg; }}
          loading={store._mainArgs.loading}
          dataSource={toJS(store._mainArgs.dataSource)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store._mainArgs.idx(i) },
            {
              title: t`任务编号`,
              width: 145,
              cell: (v, _, row) => {
                return (
                  <Button
                    key={row.id}
                    type="primary"
                    text
                    onClick={() => handleTableAction(row, 'viewTask')}
                  >
                    {row.id}
                  </Button>
                );
              },
            },
            column('areaGroup', { width: 150 }),
            column('carrierCompanyName', { width: 60 }),
            column('orderBaseModel.passengerName', { width: 58 }),
            column('driverPlate', { width: 128 }),
            column('showPrice', { width: 120 }),
            column('state', { width: 58 }),
            column('departureTime', { width: 126 }),
          ].concat(global.isAdmin ? [{
            title: t`相关订单`,
            width: 160,
            cell: (v, _, row) => {
              const { orderIds = [] } = row;
              return (
                <>
                  {orderIds.map((id, idx) => (
                    <Button
                      key={`${id}-${idx}`}
                      type="primary"
                      text
                      onClick={() => {
                        const info = {
                          orderId: id,
                          taskInfo: row,
                        };
                        handleTableAction(info, 'viewOrder');
                      }}
                    >
                      {id}
                    </Button>
                  ))}
                </>
              );
            },
          }] : []).concat([
            {
              title: t`操作`,
              dataIndex: 'orderNumber',
              width: 120,
              cell: (_, __, order) => {
                const { state, driverInfo, orderBaseModel } = order;
                const { predictTime, predictBeginDate } = orderBaseModel || {};
                const baseTime = moment(predictBeginDate).add(predictTime, 'hour');
                const curDriverInfo = store.getDriverInfo(driverInfo) || {};
                const { state: driverState } = curDriverInfo;
                const now = moment();
                let isManualFinish = false;

                if (moment(now).isAfter(moment(baseTime))) {
                  isManualFinish = true;
                }

                const funcMenu = [
                  {
                    title: '派车',
                    onClick: () => handleTableAction(order, 'sendCar'),
                    show: [TASK_STATE.WAITING].includes(state),
                  },
                  {
                    title: '编辑',
                    onClick: () => handleTableAction(order, 'editTask'),
                  },
                  {
                    title: '取消派车',
                    onClick: () => handleTableAction(order, 'cancelSendCar'),
                    show: [TASK_STATE.START].includes(state),
                  },
                  {
                    title: '干预完成',
                    onClick: () => handleTableAction(order, 'finishTask'),
                    show: [TASK_STATE.START].includes(state) && isManualFinish,
                  },
                  {
                    title: '去接乘客',
                    onClick: () => handleTableAction(order, 'pickUpPassenger'),
                    show: !isManualFinish && driverState === DRIVER_STATE.SEND_CAR,
                  },
                  {
                    title: '接到乘客',
                    onClick: () => handleTableAction(order, 'pickedPassenger'),
                    show: !isManualFinish && driverState === DRIVER_STATE.GOING,
                  },
                  {
                    title: '到达目的地',
                    onClick: () => handleTableAction(order, 'arrive'),
                    show: !isManualFinish && driverState === DRIVER_STATE.PICKED,
                  },
                ];
                return (
                  <MoreFuncDropDown
                    dropdownItems={funcMenu}
                    maxShow={1}
                  />
                );
              },
            }])}
        />
      </div>
      <TaskInfoDrawer
        visible={modal[0] === 'viewTask' || modal[0] === 'editTask'}
        task={curRef.current}
        modal={modal}
        onCancel={handleCancel}
        onClose={() => {
          setModal([]);
        }}
      />
      <SendCarDrawer
        visible={modal[0] === 'sendCar'}
        task={curRef.current}
        onClose={() => {
          setModal([]);
        }}
      />
      <OrderInfoDrawer
        visible={modal[0] === 'viewOrder'}
        orderId={curRef.current?.orderId}
        task={curRef.current?.taskInfo}
        onClose={() => {
          setModal([]);
        }}
      />
      <FinishTaskDialog
        visible={modal[0] === 'changeTaskState'}
        task={curRef.current}
        action={modal[1] || null}
        onClose={async () => {
          setModal([]);
          await store._mainArgs.query();
        }}
      />
      <CancelCarDrawer
        visible={modal[0] === 'cancelSendCar'}
        task={curRef.current}
        onClose={() => {
          setModal([]);
        }}
      />
    </TauPage>
  );
}

export default observer(CcTask);
